package org.edu.modules.system.controller;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.edu.common.api.vo.Result;
import org.edu.common.system.api.ISysBaseAPI;
import org.edu.common.util.*;
import org.edu.modules.base.service.BaseCommonService;
import org.edu.common.system.util.JwtUtil;
import org.edu.common.system.vo.LoginUser;
import org.edu.common.util.encryption.EncryptedString;
import org.edu.modules.sms.SMSUtils;
import org.edu.modules.system.entity.*;
import org.edu.modules.system.model.SysLoginModel;
import org.edu.modules.system.model.SysSimpleLoginModel;
import org.edu.modules.system.service.*;
import org.edu.modules.system.util.RandImageUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Author scott
 * @since 2018-12-17
 */
@RestController
@RequestMapping("/sys")
@Api(tags = "用户登录")
@Slf4j
public class LoginController {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private ISysLogService logService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ISysDepartService sysDepartService;
    @Autowired
    private ISysDictService sysDictService;
    @Resource
    private BaseCommonService baseCommonService;
    @Resource
    private IAppManageService iAppManageService;

    @Autowired
    private IVeBaseAppUserService veBaseAppUserService;

    private static final String BASE_CHECK_CODES = "qwertyuiplkjhgfdsazxcvbnmQWERTYUPLKJHGFDSAZXCVBNM1234567890";

    /**
     * 子系统切换
     *
     * @param
     * @return
     */
    @ApiOperation("系统切换接口")
    @RequestMapping(value = {"/convertSystem"}, method = {RequestMethod.POST})
    public Result<JSONObject> convertSystem(@RequestBody SysSimpleLoginModel sysSimpleLoginModel) {
        Result<JSONObject> result = new Result();
        String appId = sysSimpleLoginModel.getAppId();
        String token = sysSimpleLoginModel.getToken();
        if ("".equals(token) || token == null)
            return result;
        VeBaseAppUser veBaseAppUser = this.veBaseAppUserService.getUserByToken(token);
        if (veBaseAppUser == null)
            return result.error500("token");
        veBaseAppUser.setAppId(appId);
        userInfoConvertSystem(veBaseAppUser, result);
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(veBaseAppUser, loginUser);
        this.baseCommonService.addLog("用户名:" + veBaseAppUser.getUserName() + ",系统切换成功", Integer.valueOf(1), null, loginUser);
        return result;
    }

    private Result<JSONObject> userInfoConvertSystem(VeBaseAppUser veBaseAppUser, Result<JSONObject> result) {
        String syspassword = veBaseAppUser.getUserPassword();
        String username = veBaseAppUser.getUserName();
        JSONObject obj = new JSONObject();
        List<Map<String, Object>> roleList = this.veBaseAppUserService.getBaseSysRoleList(veBaseAppUser.getUserId(), veBaseAppUser.getAppId());
        String role_id = null;
        if (roleList.size() > 0) {
            int i = 0;
            role_id = ((Map) roleList.get(0)).get("id").toString();
            for (Map<String, Object> map : roleList) {
                if (i == 0) {
                    i = 1;
                    map.put("typeNum", Integer.valueOf(0));
                    continue;
                }
                map.put("typeNum", Integer.valueOf(1));
            }
        }
        obj.put("roleList", roleList);
        List<Map<String, Object>> menuList = this.veBaseAppUserService.getBaseSysMenuList(veBaseAppUser.getUserId(), veBaseAppUser.getAppId(), role_id);
        obj.put("menuList", menuList);
        List<Map<String, Object>> manageList = this.veBaseAppUserService.getBaseAppManageList(veBaseAppUser.getUserId(), veBaseAppUser.getAppId(), role_id);
        if (manageList.size() > 0)
            for (Map<String, Object> map : manageList) {
                if (map.get("id").toString().equals(veBaseAppUser.getAppId())) {
                    map.put("typeNum", Integer.valueOf(0));
                    continue;
                }
                map.put("typeNum", Integer.valueOf(1));
            }
        obj.put("manageList", manageList);
        List<Map<String, Object>> serviceList = this.veBaseAppUserService.getBaseServiceList(veBaseAppUser.getUserId());
        obj.put("serviceList", serviceList);
        if (!"".equals(veBaseAppUser.getUserType()) && veBaseAppUser.getUserType() != null) {
            Map<Object, Object> map = new HashMap<>();
            if (veBaseAppUser.getUserType().contains("1")) {
                map = this.veBaseAppUserService.getTeacherByGH(veBaseAppUser.getUserId());
                if (map != null) {
                    veBaseAppUser.setTeacherOrStudentId(map.get("id").toString());
                    veBaseAppUser.setTeacherOrStudentCode(map.get("gh").toString());
                } else {
                    veBaseAppUser.setTeacherOrStudentId("");
                    veBaseAppUser.setTeacherOrStudentCode("");
                }
            } else if (veBaseAppUser.getUserType().contains("2")) {
                map = this.veBaseAppUserService.getStudentByXH(veBaseAppUser.getUserId());
                if (map != null) {
                    veBaseAppUser.setTeacherOrStudentId(map.get("id").toString());
                    veBaseAppUser.setTeacherOrStudentCode(map.get("xh").toString());
                } else {
                    veBaseAppUser.setTeacherOrStudentId("");
                    veBaseAppUser.setTeacherOrStudentCode("");
                }
            } else {
                veBaseAppUser.setTeacherOrStudentId("");
                veBaseAppUser.setTeacherOrStudentCode("");
            }
        }
        List<Map<String, Object>> sysConfig = this.veBaseAppUserService.getVeBaseSysConfig();
        obj.put("sysConfig", sysConfig);
        obj.put("token", veBaseAppUser.getToken());
        obj.put("userInfo", veBaseAppUser);
        List<Map<String, Object>> dictionaryList = this.veBaseAppUserService.queryVeBaseDictionary();
        obj.put("dictionaryList", dictionaryList);
        obj.put("sysAllDictItems", this.sysDictService.queryAllDictItems());
        result.setResult(obj);
        result.success("系统切换成功");
        return result;
    }

    @ApiOperation("登录接口")
    @RequestMapping(value = {"/login"}, method = {RequestMethod.POST})
    public Result<JSONObject> login(@RequestBody SysLoginModel sysLoginModel) {
        Result<JSONObject> result = new Result();
        String username = sysLoginModel.getUsername();
        String password = sysLoginModel.getPassword();
        String captcha = sysLoginModel.getCaptcha();
        if (captcha == null) {
            result.error500("验证码无效");
            return result;
        }
        String lowerCaseCaptcha = captcha.toLowerCase();
        String realKey = MD5Util.MD5Encode(lowerCaseCaptcha + sysLoginModel.getCheckKey(), "utf-8");
        Object checkCode = this.redisUtil.get(realKey);
        if (checkCode == null || !checkCode.toString().equals(lowerCaseCaptcha)) {
            result.error500("验证码错误");
            return result;
        }
        LambdaQueryWrapper<VeBaseAppUser> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(VeBaseAppUser::getUserName, username);
        VeBaseAppUser veBaseAppUser = (VeBaseAppUser) this.veBaseAppUserService.getOne((Wrapper) queryWrapper);
        result = this.sysUserService.checkUserIsEffective(veBaseAppUser);
        if (!result.isSuccess())
            return result;
        String userpassword = PasswordUtil.encrypt(username, password, veBaseAppUser.getSalt());
        String syspassword = veBaseAppUser.getUserPassword();
        if (!syspassword.equals(userpassword)) {
            result.error500("用户名或密码错误");
            return result;
        }
        userInfo(veBaseAppUser, result);
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(veBaseAppUser, loginUser);
        this.baseCommonService.addLog("用户名: " + username + ",登录成功！", Integer.valueOf(1), null, loginUser);
        return result;
    }


    @ApiOperation("登录接口(免验证码)")
    @RequestMapping(value = {"/sLogin"}, method = {RequestMethod.POST})
    public Result<JSONObject> sLogin(@RequestBody SysSimpleLoginModel sysSimpleLoginModel) {
        LoginUser loginUser1 = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        VeBaseAppUser a = this.veBaseAppUserService.getAppUserByUsername(sysSimpleLoginModel.getUserId());
        Result<JSONObject> result = new Result();
        String userId = sysSimpleLoginModel.getUserId();
        if (!"".equals(sysSimpleLoginModel.getUserId()) && null != sysSimpleLoginModel.getUserId() && !"null".equals(sysSimpleLoginModel.getUserId())) {
            userId = sysSimpleLoginModel.getUserId();
        } else {
            userId = sysSimpleLoginModel.getUsername();
        }
        String password = sysSimpleLoginModel.getPassword();
        String appId = sysSimpleLoginModel.getAppId();
        result = this.veBaseAppUserService.getAppManageByAppId(appId);
        if (!result.isSuccess())
            return result;
        LambdaQueryWrapper<VeBaseAppUser> queryWrapper = new LambdaQueryWrapper();
        LambdaQueryWrapper<VeBaseAppUser> eq = queryWrapper.eq(VeBaseAppUser::getUserId, userId).eq(VeBaseAppUser::getIsDel, "0");
        //((LambdaQueryWrapper)queryWrapper.eq(VeBaseAppUser::getUserId, userId)).eq(VeBaseAppUser::getIsDel,"0");
        //VeBaseAppUser veBaseAppUser = (VeBaseAppUser)this.veBaseAppUserService.getOne((Wrapper)queryWrapper);
        //查询是否有这个用户信息
        VeBaseAppUser veBaseAppUser = (VeBaseAppUser) this.veBaseAppUserService.getOne(eq);
        //校验用户是否有效
        result = this.sysUserService.checkUserIsEffective(veBaseAppUser);
        if (!result.isSuccess())
            return result;
        result = this.veBaseAppUserService.getSrategy(userId);
        if (!result.isSuccess())
            return result;
        String userpassword = PasswordUtil.encrypt(veBaseAppUser.getUserName(), password, veBaseAppUser.getSalt());
        String syspassword = veBaseAppUser.getUserPassword();
        if (!syspassword.equals(userpassword)) {
            result = this.veBaseAppUserService.addUserAccessAndGetMessage(userId, password);
            return result;
        }
        veBaseAppUser.setAppId(appId);
        result = this.veBaseAppUserService.getSysRoleByUserIdAndAppId(veBaseAppUser.getUserId(), appId);
        if (!result.isSuccess())
            return result;
        userInfo(veBaseAppUser, result);
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(veBaseAppUser, loginUser);
        loginUser.setUsername(veBaseAppUser.getUserName());
        loginUser.setRealname(veBaseAppUser.getRealName());
        loginUser.setUserId(veBaseAppUser.getUserId());
        this.baseCommonService.addLog("用户名：" + veBaseAppUser.getUserName() + ",登录成功！", Integer.valueOf(1), null, loginUser);
        LoginUser loginUser2 = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return result;
    }

    @RequestMapping({"/logout"})
    public Result<Object> logout(HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader("X-Access-Token");
        if (oConvertUtils.isEmpty(token))
            return Result.error("退出登录失败!");
        String username = JwtUtil.getUsername(token);
        LoginUser sysUser = this.sysBaseAPI.getUserByName(username);
        if (sysUser != null) {
            this.baseCommonService.addLog("用户名:" + sysUser.getRealname() + ",退出成功!", Integer.valueOf(1), null, sysUser);
            log.info("  " + sysUser.getRealname() + ",");
            this.redisUtil.del(new String[]{"prefix_user_token_" + token});
            this.redisUtil.del(new String[]{"shiro:cache:org.edu.config.shiro.ShiroRealm.authorizationCache:" + sysUser.getId()});
            this.redisUtil.del(new String[]{String.format("%s::%s", new Object[]{"sys:cache:user", sysUser.getUsername()})});
            SecurityUtils.getSubject().logout();
            VeBaseAppUser veBaseAppUser = (VeBaseAppUser) this.veBaseAppUserService.getById(sysUser.getId());
            if (veBaseAppUser != null) {
                String resetToken = JwtUtil.sign(veBaseAppUser.getUserName(), sysUser.getPassword());
                this.redisUtil.set("prefix_user_token_" + resetToken, resetToken);
                this.redisUtil.expire("prefix_user_token_" + resetToken, 3600L);
                this.veBaseAppUserService.addUserAccess(veBaseAppUser.getUserId(), veBaseAppUser.getUserPassword(), veBaseAppUser.getRealName(), "2", "3333");
            }
            return Result.ok("退出登录成功!");
        }
        return Result.error("Token无效");
    }

    /**
     * 获取访问量
     *
     * @return
     */
    @GetMapping("loginfo")
    public Result<JSONObject> loginfo() {
        Result<JSONObject> result = new Result<JSONObject>();
        JSONObject obj = new JSONObject();
        //update-begin--Author:zhangweijian  Date:20190428 for：传入开始时间，结束时间参数
        // 获取一天的开始和结束时间
        Calendar calendar = new GregorianCalendar();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date dayStart = calendar.getTime();
        calendar.add(Calendar.DATE, 1);
        Date dayEnd = calendar.getTime();
        // 获取系统访问记录
        Long totalVisitCount = logService.findTotalVisitCount();
        obj.put("totalVisitCount", totalVisitCount);
        Long todayVisitCount = logService.findTodayVisitCount(dayStart, dayEnd);
        obj.put("todayVisitCount", todayVisitCount);
        Long todayIp = logService.findTodayIp(dayStart, dayEnd);
        //update-end--Author:zhangweijian  Date:20190428 for：传入开始时间，结束时间参数
        obj.put("todayIp", todayIp);
        result.setResult(obj);
        result.success("登录成功");
        return result;
    }

    /**
     * 获取访问量
     *
     * @return
     */
    @GetMapping("visitInfo")
    public Result<List<Map<String, Object>>> visitInfo() {
        Result<List<Map<String, Object>>> result = new Result<List<Map<String, Object>>>();
        Calendar calendar = new GregorianCalendar();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        Date dayEnd = calendar.getTime();
        calendar.add(Calendar.DAY_OF_MONTH, -7);
        Date dayStart = calendar.getTime();
        List<Map<String, Object>> list = logService.findVisitCount(dayStart, dayEnd);
        result.setResult(oConvertUtils.toLowerCasePageList(list));
        return result;
    }


    /**
     * 登陆成功选择用户当前部门
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/selectDepart", method = RequestMethod.PUT)
    public Result<JSONObject> selectDepart(@RequestBody SysUser user) {
        Result<JSONObject> result = new Result<JSONObject>();
        String username = user.getUsername();
        if (oConvertUtils.isEmpty(username)) {
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            username = sysUser.getUsername();
        }
        String orgCode = user.getOrgCode();
        this.sysUserService.updateUserDepart(username, orgCode);
        SysUser sysUser = sysUserService.getUserByName(username);
        JSONObject obj = new JSONObject();
        obj.put("userInfo", sysUser);
        result.setResult(obj);
        return result;
    }

    /**
     * 获取短信验证码接口
     *
     * @param jsonObject
     * @return
     */
    @PostMapping({"/sms"})
    public Result<String> sms(@RequestBody JSONObject jsonObject) {
        Result<String> result = new Result();
        String mobile = jsonObject.get("mobile").toString();
        log.info(mobile);
        if (oConvertUtils.isEmpty(mobile)) {
            result.setMessage("手机号不允许为空!");
            result.setSuccess(false);
            return result;
        }
        Object object = this.redisUtil.get(mobile);
        if (object != null) {
            result.setMessage("验证码10分钟内，仍然有效!");
            result.setSuccess(false);
            return result;
        }
        VeBaseAppUser veBaseAppUser = this.veBaseAppUserService.getUserByPhone(mobile);
        result = this.sysUserService.checkUserIsEffective(veBaseAppUser);
        if (!result.isSuccess()) {
            String message = result.getMessage();
            if ("该用户不存在，请注册".equals(message))
                result.error500("该用户不存在或未绑定手机号");
            return result;
        }
        String s = SMSUtils.generateValidateCode(4);
        try {
            SMSUtils.sendShortMessage("SMS_204650071", mobile, s);
            this.redisUtil.set(mobile, s);
        } catch (ClientException e) {
            e.printStackTrace();
            result.setMessage("获取验证码失败!请稍后重试");
            result.setSuccess(false);
        }
        return result;
    }


    /**
     * 手机号登录接口
     *
     * @param jsonObject
     * @return
     */
    @ApiOperation("手机号登录接口")
    @PostMapping({"/phoneLogin"})
    public Result<JSONObject> phoneLogin(@RequestBody JSONObject jsonObject) {
        Result<JSONObject> result = new Result();
        String phone = jsonObject.getString("mobile");
        VeBaseAppUser veBaseAppUser = this.veBaseAppUserService.getUserByPhone(phone);
        result = this.sysUserService.checkUserIsEffective(veBaseAppUser);
        if (!result.isSuccess())
            return result;
        String smscode = jsonObject.getString("captcha");
        Object code = this.redisUtil.get(phone);
        if (!smscode.equals(code)) {
            result.setMessage("手机验证码错误");
            return result;
        }
        userInfo(veBaseAppUser, result);
        this.baseCommonService.addLog("用户名: " + veBaseAppUser.getUserName() + ",登录成功", Integer.valueOf(1), null);
        return result;
    }

    private Result<JSONObject> userInfo(VeBaseAppUser veBaseAppUser, Result<JSONObject> result) {
        String syspassword = veBaseAppUser.getUserPassword();
        String username = veBaseAppUser.getUserName();
        String token = JwtUtil.sign(username, syspassword);
        this.redisUtil.set("prefix_user_token_" + token, token);
        this.redisUtil.expire("prefix_user_token_" + token, 43200L);
        JSONObject obj = new JSONObject();
        List<Map<String, Object>> roleList = this.veBaseAppUserService.getBaseSysRoleList(veBaseAppUser.getUserId(), veBaseAppUser.getAppId());
        String role_id = null;
        if (roleList.size() > 0) {
            int i = 0;
            role_id = ((Map) roleList.get(0)).get("id").toString();
            for (Map<String, Object> map : roleList) {
                if (i == 0) {
                    i = 1;
                    map.put("typeNum", Integer.valueOf(0));
                    continue;
                }
                map.put("typeNum", Integer.valueOf(1));
            }
        }
        obj.put("roleList", roleList);
        List<Map<String, Object>> menuList = this.veBaseAppUserService.getBaseSysMenuList(veBaseAppUser.getUserId(), veBaseAppUser.getAppId(), role_id);
        obj.put("menuList", menuList);
        List<Map<String, Object>> manageList = this.veBaseAppUserService.getBaseAppManageList(veBaseAppUser.getUserId(), veBaseAppUser.getAppId(), role_id);
        if (manageList.size() > 0)
            for (Map<String, Object> map : manageList) {
                if (map.get("id").toString().equals(veBaseAppUser.getAppId())) {
                    map.put("typeNum", Integer.valueOf(0));
                    continue;
                }
                map.put("typeNum", Integer.valueOf(1));
            }
        obj.put("manageList", manageList);
        List<Map<String, Object>> serviceList = this.veBaseAppUserService.getBaseServiceList(veBaseAppUser.getUserId());
        obj.put("serviceList", serviceList);
        if (!"".equals(veBaseAppUser.getUserType()) && veBaseAppUser.getUserType() != null) {
            Map<Object, Object> map = new HashMap<>();
            if (veBaseAppUser.getUserType().contains("1")) {
                map = this.veBaseAppUserService.getTeacherByGH(veBaseAppUser.getUserId());
                if (map != null) {
                    veBaseAppUser.setTeacherOrStudentId(map.get("id").toString());
                    veBaseAppUser.setTeacherOrStudentCode(map.get("gh").toString());
                    Map teacherDeatil = this.veBaseAppUserService.getTeacherDeatilByGH(veBaseAppUser.getUserId());
                    if (teacherDeatil != null) {
                        veBaseAppUser.setYxmc(teacherDeatil.get("YXMC")+"");
                        veBaseAppUser.setJyzmc(teacherDeatil.get("JYZMC")+"");
//                        veBaseAppUser.setNjmc(teacherDeatil.get("NJMC")+"");
                        veBaseAppUser.setZymc(teacherDeatil.get("ZYMC")+"");
//                        veBaseAppUser.setXzbmc(teacherDeatil.get("XZBMC")+"");
                    }
                } else {
                    veBaseAppUser.setTeacherOrStudentId("");
                    veBaseAppUser.setTeacherOrStudentCode("");
                }
            } else if (veBaseAppUser.getUserType().contains("2")) {
                map = this.veBaseAppUserService.getStudentByXH(veBaseAppUser.getUserId());
                if (map != null) {
                    veBaseAppUser.setTeacherOrStudentId(map.get("id").toString());
                    veBaseAppUser.setTeacherOrStudentCode(map.get("xh").toString());
                    Map studentDeatil = this.veBaseAppUserService.getStudentDeatilByXH(veBaseAppUser.getUserId());
                    if (studentDeatil != null) {
                        veBaseAppUser.setXzbmc(studentDeatil.get("XZBMC").toString());
                        veBaseAppUser.setNjmc(studentDeatil.get("NJMC").toString());
                        veBaseAppUser.setZymc(studentDeatil.get("ZYMC").toString());
                        veBaseAppUser.setYxmc(studentDeatil.get("YXMC").toString());
                    }
                } else {
                    veBaseAppUser.setTeacherOrStudentId("");
                    veBaseAppUser.setTeacherOrStudentCode("");
                }
            } else {
                veBaseAppUser.setTeacherOrStudentId("");
                veBaseAppUser.setTeacherOrStudentCode("");
            }
        }
        List<Map<String, Object>> sysConfig = this.veBaseAppUserService.getVeBaseSysConfig();
        obj.put("sysConfig", sysConfig);
        List<Map<String, Object>> dictionaryList = this.veBaseAppUserService.queryVeBaseDictionary();
        obj.put("dictionaryList", dictionaryList);
        veBaseAppUser.setToken(token);
        this.veBaseAppUserService.updateById(veBaseAppUser);
        obj.put("token", token);
        obj.put("userInfo", veBaseAppUser);
        obj.put("sysAllDictItems", this.sysDictService.queryAllDictItems());
        this.veBaseAppUserService.addUserAccess(veBaseAppUser.getUserId(), veBaseAppUser.getUserPassword(), veBaseAppUser.getRealName(), "0", "0000");
        result.setResult(obj);
        result.success("登录成功");
        return result;
    }

    private Result<JSONObject> userInfoConvertRole(VeBaseAppUser veBaseAppUser, String roleId, Result<JSONObject> result) {
        JSONObject obj = new JSONObject();
        List<Map<String, Object>> roleList = this.veBaseAppUserService.getBaseSysRoleList(veBaseAppUser.getUserId(), veBaseAppUser.getAppId());
        if (roleList.size() > 0)
            for (Map<String, Object> map : roleList) {
                if (map.get("id").toString().equals(roleId)) {
                    map.put("typeNum", Integer.valueOf(0));
                    continue;
                }
                map.put("typeNum", Integer.valueOf(1));
            }
        obj.put("roleList", roleList);
        List<Map<String, Object>> menuList = this.veBaseAppUserService.getBaseSysMenuList(veBaseAppUser.getUserId(), veBaseAppUser.getAppId(), roleId);
        obj.put("menuList", menuList);
        List<Map<String, Object>> manageList = this.veBaseAppUserService.getBaseAppManageList(veBaseAppUser.getUserId(), veBaseAppUser.getAppId(), roleId);
        if (manageList.size() > 0)
            for (Map<String, Object> map : manageList) {
                if (map.get("id").toString().equals(veBaseAppUser.getAppId())) {
                    map.put("typeNum", Integer.valueOf(0));
                    continue;
                }
                map.put("typeNum", Integer.valueOf(1));
            }
        obj.put("manageList", manageList);
        List<Map<String, Object>> serviceList = this.veBaseAppUserService.getBaseServiceList(veBaseAppUser.getUserId());
        obj.put("serviceList", serviceList);
        if (!"".equals(veBaseAppUser.getUserType()) && veBaseAppUser.getUserType() != null) {
            Map<Object, Object> map = new HashMap<>();
            if (veBaseAppUser.getUserType().contains("1")) {
                map = this.veBaseAppUserService.getTeacherByGH(veBaseAppUser.getUserId());
                if (map != null) {
                    veBaseAppUser.setTeacherOrStudentId(map.get("id").toString());
                    veBaseAppUser.setTeacherOrStudentCode(map.get("gh").toString());
                } else {
                    veBaseAppUser.setTeacherOrStudentId("");
                    veBaseAppUser.setTeacherOrStudentCode("");
                }
            } else if (veBaseAppUser.getUserType().contains("2")) {
                map = this.veBaseAppUserService.getStudentByXH(veBaseAppUser.getUserId());
                if (map != null) {
                    veBaseAppUser.setTeacherOrStudentId(map.get("id").toString());
                    veBaseAppUser.setTeacherOrStudentCode(map.get("xh").toString());
                } else {
                    veBaseAppUser.setTeacherOrStudentId("");
                    veBaseAppUser.setTeacherOrStudentCode("");
                }
            } else {
                veBaseAppUser.setTeacherOrStudentId("");
                veBaseAppUser.setTeacherOrStudentCode("");
            }
        }
        List<Map<String, Object>> sysConfig = this.veBaseAppUserService.getVeBaseSysConfig();
        obj.put("sysConfig", sysConfig);
        obj.put("token", veBaseAppUser.getToken());
        obj.put("userInfo", veBaseAppUser);
        List<Map<String, Object>> dictionaryList = this.veBaseAppUserService.queryVeBaseDictionary();
        obj.put("dictionaryList", dictionaryList);
        obj.put("sysAllDictItems", this.sysDictService.queryAllDictItems());
        result.setResult(obj);
        result.success("切换成功");
        return result;
    }

    /**
     * 获取加密字符串
     *
     * @return
     */
    @GetMapping(value = "/getEncryptedString")
    public Result<Map<String, String>> getEncryptedString() {
        Result<Map<String, String>> result = new Result<Map<String, String>>();
        Map<String, String> map = new HashMap<String, String>();
        map.put("key", EncryptedString.key);
        map.put("iv", EncryptedString.iv);
        result.setResult(map);
        return result;
    }

    /**
     * 后台生成图形验证码 ：有效
     *
     * @param response
     * @param key
     */
    @ApiOperation("获取验证码")
    @GetMapping(value = "/randomImage/{key}")
    public Result<String> randomImage(HttpServletResponse response, @PathVariable String key) {
        Result<String> res = new Result<String>();
        try {
            String code = RandomUtil.randomString(BASE_CHECK_CODES, 4);
            String lowerCaseCode = code.toLowerCase();
            String realKey = MD5Util.MD5Encode(lowerCaseCode + key, "utf-8");
            redisUtil.set(realKey, lowerCaseCode, 60L);
            String base64 = RandImageUtil.generate(code);
            res.setSuccess(true);
            res.setResult(base64);
        } catch (Exception e) {
            res.error500("获取验证码出错" + e.getMessage());
            e.printStackTrace();
        }
        return res;
    }


    @ApiOperation("app登录")
    @RequestMapping(value = {"/mLogin"}, method = {RequestMethod.POST})
    public Result<JSONObject> mLogin(@RequestBody SysLoginModel sysLoginModel) throws Exception {
        Result<JSONObject> result = new Result();
        String username = sysLoginModel.getUsername();
        String password = sysLoginModel.getPassword();
        VeBaseAppUser veBaseAppUser = this.veBaseAppUserService.getUserByName(username);
        result = this.sysUserService.checkUserIsEffective(veBaseAppUser);
        if (!result.isSuccess())
            return result;
        String userpassword = PasswordUtil.encrypt(username, password, veBaseAppUser.getSalt());
        String syspassword = veBaseAppUser.getUserPassword();
        if (!syspassword.equals(userpassword)) {
            result.error500("用户名或密码错误");
            return result;
        }
        JSONObject obj = new JSONObject();
        obj.put("userInfo", veBaseAppUser);
        String token = JwtUtil.sign(username, syspassword);
        this.redisUtil.set("prefix_user_token_" + token, token);
        this.redisUtil.expire("prefix_user_token_" + token, 3600L);
        obj.put("token", token);
        result.setResult(obj);
        result.setSuccess(true);
        result.setCode(Integer.valueOf(200));
        this.baseCommonService.addLog("用户名:" + username + ",登录成功[移动端]！", Integer.valueOf(1), null);
        return result;
    }

    /**
     * 图形验证码
     *
     * @param sysLoginModel
     * @return
     */
    @RequestMapping(value = "/checkCaptcha", method = RequestMethod.POST)
    public Result<?> checkCaptcha(@RequestBody SysLoginModel sysLoginModel) {
        String captcha = sysLoginModel.getCaptcha();
        String checkKey = sysLoginModel.getCheckKey();
        if (captcha == null) {
            return Result.error("验证码无效");
        }
        String lowerCaseCaptcha = captcha.toLowerCase();
        String realKey = MD5Util.MD5Encode(lowerCaseCaptcha + checkKey, "utf-8");
        Object checkCode = redisUtil.get(realKey);
        if (checkCode == null || !checkCode.equals(lowerCaseCaptcha)) {
            return Result.error("验证码错误");
        }
        return Result.ok();
    }
}
